﻿using System;
using System.Linq;
using BusinessBingo.Data.Filter;
using BusinessBingo.Data.Interfaces;
using BusinessBingo.Model;
using BusinessBingo.Model.Interfaces;
using BusinessBingo.Queries;
using BusinessBingo.QueryHandlers.Base;
using BusinessBingo.QueryHandlers.Interfaces;
using BusinessBingo.QueryHandlers.Results;

namespace BusinessBingo.QueryHandlers
{
    public class GetGroupQueryHandler : BaseQueryHandler, IGetGroupQueryHandler
    {
        private IGroupRepository _groupRepository;

        public GetGroupQueryHandler(
            IGroupRepository groupRepository,
            IValidationState validationState)
            : base(validationState)
        {
            this._groupRepository = groupRepository;
        }

        public GetGroupQueryHandlerResult Execute(GetGroupQuery getGroupQuery)
        {
            GetGroupQueryHandlerResult result = new GetGroupQueryHandlerResult();

            if(getGroupQuery == default(GetGroupQuery))
                throw new ArgumentNullException("GetGroupQuery");
            if (getGroupQuery.GroupId == default(Guid) && string.IsNullOrWhiteSpace(getGroupQuery.GroupUrl) == true)
            {
                this._validationState.AddError<GetGroupQuery>(x => x.GroupId, ErrorTypes.Empty);
                this._validationState.AddError<GetGroupQuery>(x => x.GroupUrl, ErrorTypes.Empty);
            }

            if(this._validationState.IsValid == false)
                return result;

            GroupFilter filter = new GroupFilter();
            if(getGroupQuery.GroupId != default(Guid))
                filter.WithId = getGroupQuery.GroupId;
            if (string.IsNullOrWhiteSpace(getGroupQuery.GroupUrl) == false)
                filter.WithUrl = getGroupQuery.GroupUrl;

            Group group = this._groupRepository.GetItems(null, null, filter).Single();
            
            result.Succeeded = true;
            result.Group = group;

            return result;
        }
    }
}